import 'package:dio/dio.dart';
import 'package:enjoy_plus/pages/tab_bar_page.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/validate.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

class HouseForm extends StatefulWidget {
  const HouseForm({super.key, required this.params});

  final Map params;

  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  final Map _formData = {
    'point': '', // 小区信息
    'building': '', // 小区楼栋信息
    'room': '', // 小区房间信息
    'name': '', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '', // 业主电话
    'idcardFrontUrl': '', // 身份证正面
    'idcardBackUrl': '', // 身份证背面
  };

  @override
  void initState() {
    super.initState();
    // _formData['point'] = widget.params['point'];
    // _formData['building'] = widget.params['building'];
    // _formData['room'] = widget.params['room'];
    // 合并对象
    _formData.addAll(widget.params);
    print(_formData);
  }

  // 定义控制器
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _mobileController = TextEditingController();

  _onSubmit() async {
    // 1. 校验表单数据
    String name = _nameController.text;
    String mobile = _mobileController.text;

    if (!Validate.validateName(name)) return;
    if (!Validate.validatePhone(mobile)) return;
    if (!Validate.validateIdCardImg(
      _formData['idcardFrontUrl'],
      _formData['idcardBackUrl'],
    )) return;

    setState(() {
      _formData['name'] = name;
      _formData['mobile'] = mobile;
    });
    try {
      // 调用接口
      final res = await http.post('/room', data: _formData);
      // 检测接口调用的结果
      if (res['code'] != 10000) return ToastUtil.showError(res['message']);
      ToastUtil.showSuccess('添加房屋成功');
      // 跳转到首页
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (context) => const TabBarPage()),
        (route) => false,
      );
    } catch (e) {
      ToastUtil.showError('网络请求出现问题!');
    }
  }

  Widget _buildAddIdcardPhoto(String tag, String info) {
    return const Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Icon(
          Icons.add,
          size: 30,
          color: Color.fromARGB(255, 85, 145, 175),
        ),
        Text(
          '上传人像面照片',
          style: TextStyle(
            color: Color.fromARGB(255, 85, 145, 175),
          ),
        ),
      ],
    );
  }

  Widget _buildIdcardPhoto(String tag, String photoUrl) {
    return Stack(
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width - 20,
          height: 300,
          child: Image.network(photoUrl, fit: BoxFit.contain),
        ),
        Positioned(
          right: 0,
          top: 0,
          child: GestureDetector(
            child: const Icon(Icons.delete, color: Colors.red),
            onTap: () {
              setState(() {
                _formData[tag] = '';
              });
            },
          ),
        )
      ],
    );
  }

  void _showBottomSheet(String tag) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(10),
          height: 180,
          child: Column(
            children: [
              ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  trailing: const Icon(Icons.arrow_forward_ios_rounded),
                  onTap: () async {
                    uploadAvatar(tag, ImageSource.camera);
                  }),
              ListTile(
                  leading: const Icon(Icons.image),
                  title: const Text('相册'),
                  trailing: const Icon(Icons.arrow_forward_ios_rounded),
                  onTap: () async {
                    uploadAvatar(tag, ImageSource.gallery);
                  })
            ],
          ),
        );
      },
    );
  }

  /// 上传图片
  uploadAvatar(String tag, ImageSource source) async {
    try {
      // 调用相册/相机
      ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: source);
      if (image == null) return;
      // 1. 调用上传接口
      final res = await http.post(
        '/upload',
        data: FormData.fromMap({
          // Fix：Web端不支持 MultipartFile.fromFile 格式
          "file": kIsWeb
              ? MultipartFile.fromBytes(
                  await XFile(image.path).readAsBytes(),
                  filename: image.name,
                  contentType: DioMediaType('image', 'png'),
                )
              : await MultipartFile.fromFile(image.path),
        }),
      );
      // 上传需检查业务状态码
      if (res['code'] != 10000) return ToastUtil.showError('上传图片失败');
      // 更新界面
      setState(() {
        _formData[tag] = res['data']['url'];
      });
      ToastUtil.showSuccess('上传图片成功');
    } catch (e) {
      print(e);
      ToastUtil.showError('上传图片失败');
    } finally {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加房屋信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.only(top: 10, bottom: 10),
        children: [
          // 房屋信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '房屋信息',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
            ),
          ),
          Container(
            color: Colors.white,
            padding:
                const EdgeInsets.only(left: 10, right: 10, top: 15, bottom: 15),
            child: Text(
              widget.params['point'] +
                  widget.params['building'] +
                  widget.params['room'],
            ),
          ),
          // 业主信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '业主信息',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
            ),
          ),
          // 业主姓名
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: TextField(
              controller: _nameController,
              maxLength: 15,
              decoration: const InputDecoration(
                labelText: '姓名',
                hintText: '请输入业主姓名',
                hintStyle: TextStyle(color: Colors.grey),
                border: InputBorder.none,
              ),
              inputFormatters: [
                LengthLimitingTextInputFormatter(10),
              ],
            ),
          ),
          // 性别
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: Row(
              children: [
                const Text(
                  '性别',
                  style: TextStyle(fontSize: 16),
                ),
                const SizedBox(width: 20),
                Radio(
                  value: 1,
                  groupValue: _formData['gender'],
                  onChanged: (value) {
                    setState(() {
                      _formData['gender'] = value ?? '';
                    });
                  },
                ),
                const Text('男'),
                const SizedBox(width: 10),
                Radio(
                  value: 0,
                  groupValue: _formData['gender'],
                  onChanged: (value) {
                    setState(() {
                      _formData['gender'] = value ?? '';
                    });
                  },
                ),
                const Text('女'),
              ],
            ),
          ),
          // 业主手机号
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: TextField(
              controller: _mobileController,
              keyboardType: TextInputType.phone,
              maxLength: 11,
              decoration: const InputDecoration(
                labelText: '手机号',
                hintText: '请输入您的手机号',
                hintStyle: TextStyle(color: Colors.grey),
                border: InputBorder.none,
              ),
            ),
          ),
          // 业主信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '本人身份证照片',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
            ),
          ),
          Container(
            padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
            child: const Text(
              '请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 12),
            ),
          ),
          // 身份证正面
          GestureDetector(
            onTap: () {
              _showBottomSheet('idcardFrontUrl');
            },
            child: Container(
              color: Colors.white,
              height: 320,
              padding: const EdgeInsets.all(10),
              child: _formData['idcardFrontUrl'] == ''
                  ? _buildAddIdcardPhoto('idcardFrontUrl', '上传人像面照片')
                  : _buildIdcardPhoto(
                      'idcardFrontUrl',
                      _formData['idcardFrontUrl'],
                    ),
            ),
          ),
          const SizedBox(height: 20),
          GestureDetector(
            onTap: () {
              _showBottomSheet('idcardBackUrl');
            },
            child: // 身份证反面
                Container(
              color: Colors.white,
              height: 320,
              padding: const EdgeInsets.all(10),
              child: _formData['idcardBackUrl'] == ''
                  ? _buildAddIdcardPhoto('idcardBackUrl', '上传国徽面照片')
                  : _buildIdcardPhoto(
                      'idcardBackUrl',
                      _formData['idcardBackUrl'],
                    ),
            ),
          ),
          const SizedBox(height: 20),
          // 提交审核
          Container(
            padding: const EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: () {
                // 提交审核
                _onSubmit();
              },
              child: const Column(
                children: [
                  SizedBox(height: 8),
                  Icon(Icons.exit_to_app),
                  Text('提交审核'),
                  SizedBox(height: 8)
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
